/*
 Copyright (c) 2007 AppScrapper authors and contributors
 
 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:
 
 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */

#import "KHFileUtil.h"


@implementation KHFileUtil


- (BOOL) pathContainsApp: (NSString *)path
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	if ([[path pathExtension] caseInsensitiveCompare: @"app"] == NSOrderedSame)
	{
		[pool release];
		
		return YES;
	}
		
	BOOL isDir;
	if ([[NSFileManager defaultManager] fileExistsAtPath: path isDirectory: &isDir] && isDir)
	{
		NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath: path];
		NSString *file = [[NSString alloc] init];
		
		while (file = [dirEnum nextObject])
		{
			//	Only go 1 level deep.
			[dirEnum skipDescendents];
			
			if ([[file pathExtension] caseInsensitiveCompare: @"app"] == NSOrderedSame)
			{
				[pool release];
				
				return YES;
			}
		}
	}
	
	[pool release];
	
	return NO;
}

- (NSMutableArray *) findAppsInFileArray: (NSArray *)files
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	NSMutableArray *appList = [[NSMutableArray alloc] init];
	NSEnumerator *fileEnum = [files objectEnumerator];
	
	id obj;
	BOOL isDir;
	
	//	Build a list of .apps that were passed to us
	while (obj = [fileEnum nextObject])
	{
		if ([[obj pathExtension] caseInsensitiveCompare: @"app"] == NSOrderedSame){
			[appList addObject: obj];
		}
		
		
		else if ([[NSFileManager defaultManager] fileExistsAtPath: obj isDirectory: &isDir] && isDir)
		{
			NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath: obj];
			id file;
			
			while (file = [dirEnum nextObject])
			{
				//	Only go 1 level deep.
				[dirEnum skipDescendents];
				
				if ([[file pathExtension] caseInsensitiveCompare: @"app"] == NSOrderedSame){
					[appList addObject: file];
				}
			}
		}
	}
	
	[pool release];
	
	return appList; 
}

@end
